// Copyright (c) MatrixFramework. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.

using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;
using TenantManagementService.Migration.Services;
using MatrixFramework.Keycloak.Abstractions.Extensions;
using MatrixFramework.Keycloak.Abstractions.Models;

namespace TenantManagementService.Migration;

/// <summary>
/// TenantManagementService迁移示例程序
/// </summary>
public class Program
{
    public static async Task Main(string[] args)
    {
        Console.WriteLine("🚀 TenantManagementService 迁移示例程序");
        Console.WriteLine("使用 MatrixFramework.Keycloak 组件库");
        Console.WriteLine("=" * 50);

        try
        {
            // 创建主机构建器
            var host = CreateHostBuilder(args).Build();

            // 运行示例
            await RunTenantManagementExamples(host);

            Console.WriteLine("\n✅ 示例程序执行完成");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"❌ 程序执行失败: {ex.Message}");
            Console.WriteLine($"详细信息: {ex}");
        }

        Console.WriteLine("\n按任意键退出...");
        Console.ReadKey();
    }

    /// <summary>
    /// 创建主机构建器
    /// </summary>
    /// <param name="args">命令行参数</param>
    /// <returns>主机构建器</returns>
    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureServices((context, services) =>
            {
                // 添加配置
                var configuration = context.Configuration;

                // 注册MatrixFramework Keycloak服务
                services.AddMatrixKeycloak(configuration);
                services.AddKeycloakMultiTenant();

                // 注册租户管理服务
                services.AddScoped<ITenantManagementService, TenantManagementService>();

                // 添加日志
                services.AddLogging(builder =>
                {
                    builder.AddConsole();
                    builder.SetMinimumLevel(LogLevel.Information);
                });
            });

    /// <summary>
    /// 运行租户管理示例
    /// </summary>
    /// <param name="host">主机</param>
    private static async Task RunTenantManagementExamples(IHost host)
    {
        using var scope = host.Services.CreateScope();
        var services = scope.ServiceProvider;

        var tenantManagementService = services.GetRequiredService<ITenantManagementService>();
        var logger = services.GetRequiredService<ILogger<Program>>();

        Console.WriteLine("\n📋 示例 1: 创建租户");
        await CreateTenantExample(tenantManagementService, logger);

        Console.WriteLine("\n📋 示例 2: 测试租户连接");
        await TestTenantConnectionExample(tenantManagementService, logger);

        Console.WriteLine("\n📋 示例 3: 同步租户");
        await SyncTenantExample(tenantManagementService, logger);

        Console.WriteLine("\n📋 示例 4: 批量同步租户");
        await BatchSyncTenantsExample(tenantManagementService, logger);

        Console.WriteLine("\n📋 示例 5: 获取租户同步状态");
        await GetTenantSyncStatusExample(tenantManagementService, logger);

        Console.WriteLine("\n📋 示例 6: 删除租户");
        await DeleteTenantExample(tenantManagementService, logger);
    }

    /// <summary>
    /// 示例 1: 创建租户
    /// </summary>
    private static async Task CreateTenantExample(ITenantManagementService tenantManagementService, ILogger logger)
    {
        try
        {
            var tenantInfo = new TenantInfo
            {
                Id = "demo-tenant-001",
                Name = "演示租户",
                Code = "DEMO001",
                Enabled = true,
                Description = "这是一个演示租户",
                AdminUser = new UserCreationInfo
                {
                    Username = "demo-admin",
                    Email = "admin@demo-tenant.com",
                    FirstName = "演示",
                    LastName = "管理员",
                    Password = "DemoAdmin123!"
                }
            };

            Console.WriteLine($"正在创建租户: {tenantInfo.Name} ({tenantInfo.Id})");
            var result = await tenantManagementService.CreateTenantAsync(tenantInfo);

            if (result.IsSuccess)
            {
                var creationResult = result.Value;
                Console.WriteLine($"✅ 租户创建成功!");
                Console.WriteLine($"   租户ID: {creationResult.TenantId}");
                Console.WriteLine($"   租户名称: {creationResult.TenantName}");
                Console.WriteLine($"   Realm名称: {creationResult.RealmName}");
                Console.WriteLine($"   管理员用户名: {creationResult.AdminUsername}");
                Console.WriteLine($"   管理控制台URL: {creationResult.AdminConsoleUrl}");
                Console.WriteLine($"   创建时间: {creationResult.CreatedAt:yyyy-MM-dd HH:mm:ss}");
            }
            else
            {
                Console.WriteLine($"❌ 租户创建失败: {result.GetErrorString()}");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "创建租户示例执行失败");
            Console.WriteLine($"❌ 示例执行失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 示例 2: 测试租户连接
    /// </summary>
    private static async Task TestTenantConnectionExample(ITenantManagementService tenantManagementService, ILogger logger)
    {
        try
        {
            var tenantId = "demo-tenant-001";
            Console.WriteLine($"正在测试租户连接: {tenantId}");

            var result = await tenantManagementService.TestTenantConnectionAsync(tenantId);

            if (result.IsSuccess)
            {
                Console.WriteLine($"✅ 租户连接测试成功: {(result.Value ? "已连接" : "未连接")}");
            }
            else
            {
                Console.WriteLine($"❌ 租户连接测试失败: {result.GetErrorString()}");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "测试租户连接示例执行失败");
            Console.WriteLine($"❌ 示例执行失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 示例 3: 同步租户
    /// </summary>
    private static async Task SyncTenantExample(ITenantManagementService tenantManagementService, ILogger logger)
    {
        try
        {
            var tenantId = "demo-tenant-001";
            Console.WriteLine($"正在同步租户: {tenantId}");

            var result = await tenantManagementService.SyncTenantAsync(tenantId);

            if (result.IsSuccess)
            {
                var syncResult = result.Value;
                Console.WriteLine($"✅ 租户同步成功!");
                Console.WriteLine($"   租户ID: {syncResult.TenantId}");
                Console.WriteLine($"   租户名称: {syncResult.TenantName}");
                Console.WriteLine($"   同步状态: {syncResult.Status}");
                Console.WriteLine($"   同步时间: {syncResult.SyncTime:yyyy-MM-dd HH:mm:ss}");
                Console.WriteLine($"   成功操作数: {syncResult.SuccessfulOperations.Count}");
                Console.WriteLine($"   失败操作数: {syncResult.FailedOperations.Count}");

                if (syncResult.FailedOperations.Any())
                {
                    Console.WriteLine("   失败操作详情:");
                    foreach (var error in syncResult.FailedOperations)
                    {
                        Console.WriteLine($"     - {error.Operation}: {error.ErrorMessage}");
                    }
                }
            }
            else
            {
                Console.WriteLine($"❌ 租户同步失败: {result.GetErrorString()}");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "同步租户示例执行失败");
            Console.WriteLine($"❌ 示例执行失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 示例 4: 批量同步租户
    /// </summary>
    private static async Task BatchSyncTenantsExample(ITenantManagementService tenantManagementService, ILogger logger)
    {
        try
        {
            var tenantIds = new List<string>
            {
                "demo-tenant-001",
                "demo-tenant-002",
                "demo-tenant-003"
            };

            Console.WriteLine($"正在批量同步租户: {string.Join(", ", tenantIds)}");

            var result = await tenantManagementService.SyncTenantsAsync(tenantIds);

            if (result.IsSuccess)
            {
                var batchResult = result.Value;
                Console.WriteLine($"✅ 批量租户同步成功!");
                Console.WriteLine($"   批次ID: {batchResult.BatchId}");
                Console.WriteLine($"   总租户数: {batchResult.TotalTenants}");
                Console.WriteLine($"   成功数量: {batchResult.SuccessCount}");
                Console.WriteLine($"   失败数量: {batchResult.FailedCount}");
                Console.WriteLine($"   进度: {batchResult.ProgressPercentage:F1}%");
                Console.WriteLine($"   开始时间: {batchResult.StartTime:yyyy-MM-dd HH:mm:ss}");

                if (batchResult.EndTime.HasValue)
                {
                    Console.WriteLine($"   结束时间: {batchResult.EndTime.Value:yyyy-MM-dd HH:mm:ss}");
                    Console.WriteLine($"   耗时: {batchResult.DurationSeconds:F1}秒");
                }

                if (batchResult.TenantResults.Any())
                {
                    Console.WriteLine("   各租户同步结果:");
                    foreach (var tenantResult in batchResult.TenantResults)
                    {
                        Console.WriteLine($"     - {tenantResult.TenantName}: {tenantResult.Status}");
                    }
                }
            }
            else
            {
                Console.WriteLine($"❌ 批量租户同步失败: {result.GetErrorString()}");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "批量同步租户示例执行失败");
            Console.WriteLine($"❌ 示例执行失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 示例 5: 获取租户同步状态
    /// </summary>
    private static async Task GetTenantSyncStatusExample(ITenantManagementService tenantManagementService, ILogger logger)
    {
        try
        {
            var tenantId = "demo-tenant-001";
            Console.WriteLine($"正在获取租户同步状态: {tenantId}");

            var result = await tenantManagementService.GetTenantSyncStatusAsync(tenantId);

            if (result.IsSuccess)
            {
                var status = result.Value;
                Console.WriteLine($"✅ 获取租户同步状态成功!");
                Console.WriteLine($"   租户ID: {status.TenantId}");
                Console.WriteLine($"   租户名称: {status.TenantName}");
                Console.WriteLine($"   同步状态: {status.Status}");
                Console.WriteLine($"   进度: {status.ProgressPercentage}%");
                Console.WriteLine($"   当前操作: {status.CurrentOperation}");

                if (status.LastSyncTime.HasValue)
                {
                    Console.WriteLine($"   最后同步时间: {status.LastSyncTime.Value:yyyy-MM-dd HH:mm:ss}");
                }

                if (!string.IsNullOrEmpty(status.ErrorMessage))
                {
                    Console.WriteLine($"   错误信息: {status.ErrorMessage}");
                }

                if (status.RetryCount > 0)
                {
                    Console.WriteLine($"   重试次数: {status.RetryCount}");
                }
            }
            else
            {
                Console.WriteLine($"❌ 获取租户同步状态失败: {result.GetErrorString()}");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "获取租户同步状态示例执行失败");
            Console.WriteLine($"❌ 示例执行失败: {ex.Message}");
        }
    }

    /// <summary>
    /// 示例 6: 删除租户
    /// </summary>
    private static async Task DeleteTenantExample(ITenantManagementService tenantManagementService, ILogger logger)
    {
        try
        {
            var tenantId = "demo-tenant-001";
            Console.WriteLine($"正在删除租户: {tenantId}");
            Console.WriteLine("⚠️  注意: 这将删除租户的所有数据，请谨慎操作!");

            var result = await tenantManagementService.DeleteTenantAsync(tenantId);

            if (result.IsSuccess)
            {
                Console.WriteLine($"✅ 租户删除成功: {tenantId}");
            }
            else
            {
                Console.WriteLine($"❌ 租户删除失败: {result.GetErrorString()}");
            }
        }
        catch (Exception ex)
        {
            logger.LogError(ex, "删除租户示例执行失败");
            Console.WriteLine($"❌ 示例执行失败: {ex.Message}");
        }
    }
}